package com.zsj.juc.completableFuture;

import java.util.concurrent.*;

/**
 * @author zsj
 * @version 1.0
 * @date 2024/4/18 21:52
 * @description
 */
public class CompletionStageTest {
    public static void main(String[] args) throws Exception {
   /*     CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                try {
                    TimeUnit.MILLISECONDS.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "success";
        });*/
//        completableFuture.get();//阻塞 一直等待结果
//        completableFuture.get(2, TimeUnit.SECONDS);//过时不候 TimeoutException
//        completableFuture.join();
        //此方法是  如果计算完成返回正常结果值 否则返回你传的值
//        System.out.println(completableFuture.getNow("xxx"));

        //打断运算 直接将这个值返回
//        completableFuture.complete("completeValue" + completableFuture.join());


        //对计算结果进行处理
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        //thenApply  exceptionally  like (try catch)计算结果如果存在依赖关系 这两个线程串行化
        //handle  exceptionally  like (try finally)最终会执行exceptionally的方法 就算有异常也会往下执行
        CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int result = ThreadLocalRandom.current().nextInt(10);
            System.out.println("刚计算出来的结果" + result);
            return result;
        }, threadPool).handle((f, e) -> {
            System.out.println("2上一次的计算结果" + f);
            return f + 1;
        }).handle((f, e) -> {
            System.out.println("3上一次的计算结果" + f);
            return f + 2;
        }).whenComplete((v, e) -> {
            if (e == null) {
                System.out.println("最终计算结果" + v);
            }
        }).exceptionally(e -> {
            e.printStackTrace();
            System.out.println("exceptionally come in");
            System.out.println(e.getMessage());
            return null;
        });
        System.out.println(Thread.currentThread().getName() + "主线程");
        threadPool.shutdown();
    }

}
